<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 用户模型
 *
 * @author www.dingwei.cn
 */

class CtyUserModel extends MY_Model{
	
	public $tbCounty= 'admin_county';
	public $tbCountyItem = 'admin_county_item';
	public $tbLocation = 'admin_location';
	public $tbSession = 'admin_county_session';
    private $tbRole = 'admin_role';
	/**
	 * 获取用户信息通过session
	 *
	 * @param	string $sessionid	会话id
	 * @return	array
	 */
	public function getUserInfoBySessionid($sessionid){
	
		if( ! $sessionid){
			return array();
		}
		$this->db->select('u.manager,u.status,u.section_name,u.id,se.ip,r.permissions')
				->join($this->tbCounty.' u', 'u.id = se.county_id')
            ->join($this->tbRole.' r', 'r.id = u.role_id', 'left')
				->where(array('se.sessionid' => $sessionid));
		$tA = $this->getOne($this->tbSession.' se');
		if( ! $tA){
			return array();
		}
		
		$tA['county'] = $this->getCountyIds($tA['id']);
		return $tA;
	}
	
	/**
	 * 添加登录sessionid
	 *
	 * @param	integer $userId		用户id
	 * @param	string	$sessionid	会话id
	 * @return	boolean
	 */
	public function addSession($userId, $sessionid){
			
		if( ! $userId || ! $sessionid){
			return false;
		}
			
		$data = array(
				'county_id' => $userId,
				'sessionid' => $sessionid,
				'ip' => getClientIp(),
				'updatetime' => time(),
				'addtime' => time()
		);
			
		$query = $this->insert($this->tbSession, $data);
		if( ! $query){
			$this->db->where(array('user_id' => $userId, 'addtime <=' => time() - 24 * 3600 * 2));
			return false;
		}
			
		return true;
	}
	
	/**
	 * 删除登录会话
	 *
	 * @param string $sessionId
	 */
	public function deleteSessionId($sessionId){
			
		if( ! $sessionId) return false;
		$this->db->where('sessionid', $sessionId);
		return $this->delete($this->tbSession);
	}
	
	/**
	 * 获取用户信息通过账号和密码
	 *
	 * @param	string	$account	账号
	 * @param	string	$password	密码
	 * @return	array
	 */
	public function getInfoByAccountAndPassword($account, $password){
	
		if( ! $account || ! $password){
			return array();
		}
		$this->db->select('u.manager,u.status,u.id')
		->where(array('u.account' => $account,
				'password' => $password,
		));
		$tA = $this->getOne($this->tbCounty.' u');
		if( ! $tA){
			return array();
		}
			
		return $tA;
	}
	
	/**
	 * 获取管理员所管辖的区域
	 * @param 	mixed 	$id
	 * @param 	bool 	$isCi
	 * @return	array
	 */
	public function getCountyItem($id, $isCi = false){
		
		$this->db->select('l.admin_id,l.province_id,p.name as province,
				l.city_id,c.name as city,l.county_id,i.name as county')	
		         ->join($this->tbLocation.' p', 'p.id = l.province_id')
		         ->join($this->tbLocation.' c', 'c.id = l.city_id')
		         ->join($this->tbLocation.' i', 'i.id = l.county_id');
		if(is_array($id)){
			$this->db->where_in('l.admin_id', $id);	
			$tA = $this->getAll($this->tbCountyItem.' l');
			$data = [];
			foreach ($tA as $v){
				if( ! isset($data[$v['admin_id']])){
					$data[$v['admin_id']] = [];
				}
				$data[$v['admin_id']][] = $v;
			}
			
			return $data;
		}else{
			$this->db->where('admin_id', $id);
		}
		
		$tA = $this->getAll($this->tbCountyItem.' l');

        $data = [];
		if ($isCi){
            foreach ($tA as $v){
                if(isset($v['county_id']) && !in_array($v['county_id'], $data)){
                    $data[] = $v['county_id'];
                }
            }
        }else{
            foreach ($tA as $v){
                if( ! isset($data[$v['city_id']])){
                    $data[$v['city_id']] = [
                        'province_id' => $v['province_id'],
                        'province' => $v['province'],
                        'city_id' => $v['city_id'],
                        'city' => $v['city'],
                        'county' => [],
                    ];
                }

                $data[$v['city_id']]['county'][] = ['id' => $v['county_id'], 'name' => $v['county']];
            }
        }

		
		return array_values($data);
	}
	
	/**
	 * 获取详情
	 * @param integer $id
	 * @param boolean $min
	 * @return array
	 */
	public function getInfo($id, $min = false){
	
		if($min){
			$this->db
				->select('id,status')
				->where('id', $id);
			return $this->getOne($this->tbCounty);
		}
		
		$this->db->select('id,account,section_name,manager,mobile,mobile,status,addtime')
				 ->where('id', $id);
		$data = $this->getOne($this->tbCounty);
		if($data){
			$data['area'] = $this->getCountyItem($id);	
		}
		
		return $data;
	}
	
	/**
	 * 判断账号是否存在
	 * @param string $account
	 * @param number $notId
	 * @return	boolean
	 */
	public function accountIsExist($account, $notId = 0){
		
		$this->db->where('account', $account);
		if($notId){
			$this->db->where('id <>', $notId);
		}
		
		if($this->count($this->tbCounty)){
			return true;
		}
		
		return false;
	}
	
	/**
	 * 获取区域ids
	 * @param 	integer $userId
	 * @return	array
	 */
	public function getCountyIds($userId, $all = false, $flag = 1, $name = false){
		
		static $tmp = [];
		
		if( ! $tmp){
			$this->db->select('province_id,city_id,county_id')
					 ->where('admin_id', $userId);
			$tmp = $this->getAll($this->tbCountyItem);
		}
		
		if( ! $all){
			$this->db->select('county_id')
					 ->where('admin_id', $userId);
			$data = []; 
			$tA = $this->getAll($this->tbCountyItem);
			foreach ($tmp as $v){
				$data[] = $v['county_id'];
			}
			
			return $data;
		}
		
		$province = [];
		$city = [];
		$county = [];
		$tA = $tmp;
		if($flag == 2){
			
			if($name){
				get_instance()->loadModel('AdmSettingModel', 'mSett', 'admin');
				$ids = [];
				foreach ($tA as $v){
					if( ! in_array($v['province_id'], $ids)){
						$ids[] = $v['province_id'];
					}
					
					if( ! in_array($v['city_id'], $ids)){
						$ids[] = $v['city_id'];
					}
					
					$ids[] = $v['county_id'];
				}
				$tA1 = $this->mSett->getLocationNameByIds($ids);				
				foreach ($tA as $k => $v){
					$tA[$k]['province'] = isset($tA1[$v['province_id']]) ? $tA1[$v['province_id']]['name'] : '';				
					$tA[$k]['city'] = isset($tA1[$v['city_id']]) ? $tA1[$v['city_id']]['name'] : '';				
					$tA[$k]['county'] = isset($tA1[$v['county_id']]) ? $tA1[$v['county_id']]['name'] : '';				
				}
				
			}
			
			return $tA;
		}
		
		foreach ($tA as $v){
			
			if( ! in_array($v['province_id'], $province)){
				$province[] = $v['province_id'];
			}
			
			if( ! in_array($v['city_id'], $city)){
				$city[] = $v['city_id'];
			}
			
			if( ! in_array($v['county_id'], $county)){
				$county[] = $v['county_id'];
			}
		}
		
		return [
				'province' => $province,
				'city' => $city,
				'county' => $county
		];
	}
}